const DynamicModel = require('../../model/dynamicmodel')
const {
	pageCompanyDynamic,
	pageMediaReport,
	pageIndustryNews,
	pageIndustyInformation
} = require("../../request/home")
const {
	CodeEnum,
	AreaEnum
} = require("../../enum")
const {
	isString,
	isArray,
	now,
	suc,
	err,
	exc
} = require("../../utils")

module.exports = class HomeLogic {
	static get _model() {
		return new DynamicModel()
	}

	static async addDataListInfo(req, type) {
		let list = []
		let listLg = 0
		let index = 1
		do {
			const {
				data: {
					content = []
				} = {}
			} = await req(index) || {}
			listLg = content.length
			if (listLg) {
				list.push(...content)
			}
			index++
		}
		while (listLg)
		const dynamicModel = new DynamicModel();
		const curDateTime = now()
		const preList = list.map(mi => {
			const model = dynamicModel.getNeatInstance()
			model.keywords = mi.keywords // 关键字
			model.title = mi.title // 标题
			model.content = mi.content // 内容
			model.refLink = mi.refLink //来源路径
			model.preview_img = mi.smallImg // 预览图片
			model.refName = mi.refName //来源]
			model.type = type
			model.create_date = curDateTime //创建日期
			model.lastupdate_date = curDateTime //更新日期
			return model
		})

		// 插入数据 
		const {
			inserted
		} = await dynamicModel.insert(preList)
		return inserted
	}

	async removeAllToDynamic() {
		const dynamicModel = new DynamicModel();
		return await dynamicModel.removeAll()
	}

	static async addCompanyDynamicInfo() {
		try {
			const map = new Map([
				[pageCompanyDynamic, AreaEnum.COMPANY_DYNAMIC_CODE],
				[pageMediaReport, AreaEnum.MEDIA_REPORT_CODE],
				[pageIndustryNews, AreaEnum.INDUSTRY_NEWS_CODE],
				[pageIndustyInformation, AreaEnum.INDUSTRY_INFORMATION_CODE],
			])

			for (let [key, val] of map.entries()) {
				await HomeLogic.addDataListInfo(key, val)
			}
			return suc()
		} catch (e) {
			return exc(e)
		}
	}

	static async getHotDynamicSort() {
		try {
			const {
				data = []
			} = await HomeLogic._model.getHotDynamicSort()
			return suc(data)
		} catch (e) {
			return exc(e)
		}
	}

	static async pageDynamicByType({
		id = "",
		type = ""
	} = {}) {
		try {
			const {
				data
			} = await HomeLogic._model.pageDynamicByType({
				id,
				type
			})
			console.log("data",data);
			if (!data) {
				return err('分页获取公司动态数据失败')
			}
			return suc(data)


		} catch (e) {
			return exc(e)
		}
	}

}
